var app = getApp()
var util = require('../../utils/util.js')
var api = require('../../config/api.js');
var user = require('../../utils/user.js');
Page({
  data: {
    display:false,
    step:'',
    needAuth: true,
    agent: null,
    payedCount: 0,
    shippedCount: 0,
    needAudit: 1,
    config: 0,
    unpayedCount: 0,
    complateCount: 0,
    groupingCount: 0,
    navbar_bgcolor: wx.getStorageSync('navbar_bgcolor'),
    other_bgcolor: wx.getStorageSync('other_bgcolor'),
    hasLogin: false,
    userInfo: {
      nickName: '点击登录',
      avatarUrl: '/style/images/my.png',
      step:'0'
    },
    carModel: '',
    dialogShow: false,
    buttons: [{ text: '取消' }, { text: '确定' }]
  },

  
  onLoad: function (option) {
    let that = this;
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
    if (wx.getStorageSync("navUrl")) {
      that.setData({
        navUrl: wx.getStorageSync("navUrl")
      })
    } else {
      that.setData({
        navUrl: '/pages/index/index'
      })
    }

    wx.login({
      success: function (res) {
        if (res.code) {
          that.setData({
            code: res.code
          })
        }
      }
    });
     this.getStep();
     this.state();
  },
    // 去stu表取合同的签署状态判断是否认证完成
 state:function () {
  var that = this;
  var userid = wx.getStorageSync("userid");
  console.log(userid)
  util.request(api.getsigningStatus, {userid:userid}).then(function (res) {
    if(res.data === "0"){
     that.setData({
       display:true
     })
    }
  })  
},
  getStep:function(){
     var that = this;
    var userid = wx.getStorageSync("userid");
    util.request(api.getStepByUid, {id:userid}).then(function (res) {
      that.setData({
        step:res.data
      })
    })
  },
  //重新授权
 again:function(){
  var that = this;
  console.log("重新获取签署链接")
  var auth = null;
  var userid = wx.getStorageSync("userid");
  util.request(api.againHtUrl, {userid:userid}).then(function (res) {
   if(res.errno === 0){
     console.log(res)
      //跳转认证页面
      wx.navigateTo({
        url: '/pages/signupV3/authurl'
      })
   }else{
    wx.showModal({
      title: '提示',
      content: '获取签约链接异常，请联系管理员!',
      showCancel: false
    })
   }
 })  
 },
  onShow: function () {
    var that = this;
    //console.log('个人加载中....'+app.globalData.hasLogin);
    /***************从服务器获取用户数据****************/
    var hasLogin = wx.getStorageSync("app.globalData.hasLogin");
      /*************************登陆授权************************* */
      if (hasLogin) {
        let userInfo = wx.getStorageSync('userInfo');
        this.setData({
          userInfo: userInfo,
          hasLogin: true
        });
        //获取用户信息
        var userid = wx.getStorageSync("userid");
        
        util.request(api.getUserDetailUrl, {id:userid,key:api.key}).then(function (res) {
          if(res.errno === 0){
            //console.log(res)
          var nickname = res.data.name;
          var avatar = res.data.avatar;
          var step = res.data.step;
          //console.log(JSON.stringify(res.data));
          //console.log(step);
          that.setData({
            ['userInfo.nickName']:nickname,
            ['userInfo.avatar']:avatar,
            ['userInfo.step']:step
          })
          }else if(res.errno === 402){
            wx.showModal({
              title: '错误',
              content:'不被允许的请求',
              showCancel: false
            })
          }
          //console.log(that.data.userInfo.step);
        })

      }
  },
  goLogin() {
    if (!this.data.hasLogin) {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    }
  },
  bindClearUser(){
    console.log("清理用户授权信息了");
    wx.setStorageSync("app.globalData.hasLogin",false);
    wx.setStorageSync("userid","");
      wx.showModal({
        title: '微信授权',
        content: '微信授权清理成功！',
        showCancel: false
      });
  },
  openCert(){
    if(this.data.step != 'F'){
      wx.showToast({
        title: '缴费成功之后才能查看当前功能！',
        icon: 'none',
        duration: 1500
      })
      return;
    }
    if (this.data.hasLogin) {//进行判断用户是否授权
      var userid = wx.getStorageSync("userid");
      if(userid == ''){
        wx.navigateTo({
          url: "/pages/auth/login/login"
        });
        return;
      }
      //进行跳转到学员中心
      wx.navigateTo({
        url: "/pages/user/cert/cert"
      });
    }
  },
  bindUser(){
    if (this.data.hasLogin) {
      wx.navigateTo({
        url: '/pages/user/bindUser',
      })
    } else {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    };
  },
  getUserProfile:function() {
    wx.navigateTo({
      url: "/pages/auth/login/login"
    });
  },
  getUserProfilelog:function() {
    console.log("程序走到这里了！V2.1");
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (resp) => {
        //console.log(JSON.stringify(resp.data));
        //登录远程服务器
        this.loginByWeixin(resp);
        //console.log("程序走到这里了！V2.0");
      }
    })
  },
  loginByWeixin: function (e) {
    //console.log("程序走到这里了！V3.0"+JSON.stringify(e.userInfo));
    let that = this;
    if (e.userInfo == undefined) {
      app.globalData.hasLogin = false;
      wx.setStorageSync("app.globalData.hasLogin",false);
      util.showErrorToast('微信登录失败');
      return;
    }
    //user.checkLogin().catch(() => {

      user.loginByWeixin(e.userInfo).then(res => {
        console.log("微信授权登陆成功！");
        wx.setStorageSync("app.globalData.hasLogin",true);
        app.globalData.hasLogin = true;
        that.setData({
          userInfo: e.userInfo,
          hasLogin: true
        });

      }).catch((err) => {
        app.globalData.hasLogin = false;
        wx.setStorageSync("app.globalData.hasLogin",false);
        that.setData({
          hasLogin: false
        });
        util.showErrorToast('微信登录失败');
      });
    //});



  },
  bindGetUserInfo: function (e) {
    //登录远程服务器
    this.loginByWeixin(e.detail)
  },
  wxLogin: function (e) {
    var that = this;
    //console.log(e.detail.userInfo)
    /*
    if (e.detail.userInfo == undefined) {
      app.globalData.hasLogin = false;
      that.setData({
        hasLogin: false
      });
      util.showErrorToast('微信登录失败');
      return;
    }


    user.checkLogin().catch(() => {

      user.loginByWeixin(e.detail.userInfo).then(res => {
        app.globalData.hasLogin = true;
        that.setData({
          userInfo: e.detail.userInfo,
          hasLogin: true
        });

      }).catch((err) => {
        app.globalData.hasLogin = false;
        that.setData({
          hasLogin: false
        });
        util.showErrorToast('微信登录失败');
      });
    });*/
  },

  navigateToPhysical: function () {
    //console.log(this.data.step)
    if(this.data.step != 'F'){
      wx.showToast({
        title: '缴费成功之后才能查看当前功能！',
        icon: 'none',
        duration: 1500
      })
      return;
    }
    if (this.data.hasLogin) {
      wx.navigateTo({
        url: '/pages/healthcheckup/index',
      });
    } else {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    };
  },
  navigateToLearnTime: function () {
    if(this.data.step != 'F'){
      wx.showToast({
        title: '缴费成功之后才能查看当前功能！',
        icon: 'none',
        duration: 1500
      })
      return;
    }
    if (this.data.hasLogin) {
      wx.navigateTo({
        url: '/pages/learntime/index',
      })
    } else {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    };
  },
  navigateToResult: function () {
    if(this.data.step != 'F'){
      wx.showToast({
        title: '缴费成功之后才能查看当前功能！',
        icon: 'none',
        duration: 1500
      })
      return;
    }
    if (this.data.hasLogin) {
      wx.navigateTo({
        url: '/pages/result/index',
      })
    } else {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    };
  },
  toTrain: function () {
    if(this.data.step != 'F'){
      wx.showToast({
        title: '缴费成功之后才能查看当前功能！',
        icon: 'none',
        duration: 1500
      })
      return;
    }
    if (this.data.hasLogin) {
      wx.navigateTo({
        url: '/pages/train/record/index',
      })
    }else{
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    }



    /*wx.showLoading({
      title: '加载中...'
    })*/
    /*util.request(api.AppointmentMySchoolInfo, {}).then(function (res) {
      //wx.hideLoading();
      if (res.errno === 0) {//须根据当前学员step状态判断是否可进行预约
        var data = res.data;
        wx.hideLoading();
        wx.navigateTo({
          url: '/pages/train/clause/index?userName=' + data.userName+'&phone='+data.phone,
        })
      } else if (res.errno === 507) {
        //wx.hideLoading();
        wx.showModal({
          title: '提示',
          content: '您还未报名...',//报名进行中... 0912
          showCancel: false
        })
      } else if (res.errno === 508) {
       // wx.hideLoading();
        wx.showModal({
          title: '提示',
          content: '请完成评价后，继续进行预约',
          confirmText: '去评价',
          confirmColor: '#4169E1',
          success(res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/train/record/index?type=0',
              })
            }
          }
        })
      }
    });*/
  },
  toExam: function () {
    if(this.data.step != 'F'){
      wx.showToast({
        title: '缴费成功之后才能查看当前功能！',
        icon: 'none',
        duration: 1500
      })
      return;
    }
    wx.navigateTo({
      url: '/pages/exam/index'
    })
  },
  navigateToMySchool: function () {
    if (this.data.hasLogin) {
      var userid = wx.getStorageSync("userid");
      if(userid == ''){
        wx.navigateTo({
          url: "/pages/auth/login/login"
        });
        return;
      }
      if(this.data.step != 'F'){
        wx.showToast({
          title: '缴费成功之后才能查看当前功能！',
          icon: 'none',
          duration: 1500
        })
        return;
      }
      util.request(api.MySchoolInfo, {uid:userid,key:api.key}).then(function (res) {
        if (res.errno === 0) {
          wx.navigateTo({
            url: '/pages/myschool/detail/detail?id=' + res.data.schoolId
          })
        }else if(res.errno === 402){
          wx.showModal({
            title: '错误',
            content:'不被允许的请求',
            showCancel: false
          }) 
        }else {
          wx.showModal({
            title: '提示',
            content: res.errmsg,
            showCancel: false
          })
          //util.showInfoToast(res.errmsg);
        }
        // wx.hideLoading();
      });
    } else {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    };
  },
  navigateToSuggestionbox: function () {
    var userid = wx.getStorageSync("userid");
    console.log("useriduseriduseriduseriduserid::::"+userid);
      if(userid == ''){
        wx.navigateTo({
          url: "/pages/auth/login/login"
        });
        return;
      }
      //console.log("user::::::::"+userid);
      util.request(api.stuPayToYjx, {uid:userid}).then(function (res) {
        //console.log(JSON.stringify(res));
        if(res.data == false){
          //console.log(res.data);
          wx.showToast({
            title: '缴费成功之后才能查看当前功能！',
            icon: 'none',
            duration: 1500
          })
          /*wx.showModal({
            title: '提示',
            content: '您还不是学员，请先报名缴费！',
            showCancel: false
          })*/
        }else{
          wx.navigateTo({
            url: '/pages/suggestionbox/index',
          })
        }
      });




    /*if (this.data.hasLogin) {
      wx.navigateTo({
        url: '/pages/suggestionbox/index',
      })
    } else {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    };*/
  },
  navigateToMyCoach: function () {
    if (this.data.hasLogin) {
      var userid = wx.getStorageSync("userid");
      if(userid == ''){
        wx.navigateTo({
          url: "/pages/auth/login/login"
        });
        return;
      }
      if(this.data.step != 'F'){
        wx.showToast({
          title: '缴费成功之后才能查看当前功能！',
          icon: 'none',
          duration: 1500
        })
        return;
      }
      util.request(api.MySchoolInfo, {uid:userid,key:api.key}).then(function (res) {
        if (res.errno === 0) {
          wx.navigateTo({
            url: '/pages/mycoach/detail/detail?id=12',
          })
        }else if(res.errno === 402){
          wx.showModal({
            title: '错误',
            content:'不被允许的请求',
            showCancel: false
          })
      } else {
          /*wx.showModal({
            title: '提示',
            content: res.errmsg,
            showCancel: false
          })*/
          util.showInfoToast(res.errmsg);
        }
        // wx.hideLoading();
      });
    } else {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    };
  },
  toEval: function () {
    if (this.data.hasLogin) {
      // wx.navigateTo({
      //   url: '/pages/eval/school/add?schoolId=3268&schoolName=大学城驾校',
      // })
      var userid = wx.getStorageSync("userid");
      if(userid == ''){
        wx.navigateTo({
          url: "/pages/auth/login/login"
        });
        return;
      }
      util.request(api.LearnTimeMySchoolInfo, {uid:userid,key:api.key}).then(function (res) {
        if (res.errno === 0) {
          var data = res.data;
          wx.navigateTo({
            url: '/pages/eval/school/add?schoolId=' + data.schoolId + '&schoolName=' + data.schoolName + '&userName=' + data.userName,
          })
        } else if (res.errno === 507) {
          wx.showModal({
            title: '提示',
            content: 'res.errmsg',
            showCancel: false
          })
          //util.showInfoToast(res.errmsg);
        } else if (res.errno === 509) {
          wx.showModal({
            title: '提示',
            content: res.errmsg,
            showCancel: false
          })
        }else if(res.errno === 402){
          wx.showModal({
            title: '错误',
            content:'不被允许的请求',
            showCancel: false
          })
      }
        // wx.hideLoading();
      });

    } else {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    }

  },
  navaigateToPayInfo: function () {
    if(this.data.step != 'F'){
      wx.showToast({
        title: '缴费成功之后才能查看当前功能！',
        icon: 'none',
        duration: 1500
      })
      return;
    }
    if (this.data.hasLogin) {
      wx.navigateTo({
        url: '/pages/payinfo/index',
      })
    } else {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    };
  },
  navigateTorefund: function () {
    if (this.data.hasLogin) {
      var userid = wx.getStorageSync("userid");
      if(userid == ''){
        wx.navigateTo({
          url: "/pages/auth/login/login"
        });
        return;
      }
      util.request(api.MySchoolInfo, {uid:userid,key:api.key}).then(function (res) {
        if (res.errno === 0) {
          wx.navigateTo({
            url: '/pages/refund/clause/index?userName=' + res.data.userName,
          })
        }else if(res.errno === 402){
          wx.showModal({
            title: '错误',
            content:'不被允许的请求',
            showCancel: false
          })
      } else {
          /*wx.showModal({
            title: '提示',
            content: res.errmsg,
            showCancel: false
          })*/
          util.showInfoToast(res.errmsg);
        }
        // wx.hideLoading();
      });

    } else {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    };
  },
  onPullDownRefresh: function () {
    this.onShow();
    wx.stopPullDownRefresh();
  },
  /**
   * 点击授权登录
   */
  bindGetUserInfo: function (e) {
    var that = this
    if (e.detail.userInfo) {
      that._login();
    }
  },

  /**
   * 登录
   */
  _login: function () {
    var me = this;
    util.login(app, function (res) {
      me.setData({
        userInfo: res,
        needAuth: false,
        buyer: res || null,
        buyerScore: res.score || 0,
        state: 'ok'
      });
      // wx.navigateBack({
      //   delta: 1
      // }) 
      wx.setStorageSync('needAuth', false);
      //me._getUserIndexData(me);
    });
  },
  openConfirm: function () {
    this.setData({
      dialogShow: true
    })
  },
  tapDialogButton(e) {
    //console.log(e.detail.index);//0为取消  1为确认
    this.setData({
      dialogShow: false
    })
    return;
    var index = e.detail.index;
    if (index == 1) {//确认
      if (this.data.carModel == '') {
        util.showErrorToast('请选择车型');
        return;
      }
      if (this.data.hasLogin == false) {
        wx.navigateTo({
          url: "/pages/auth/login/login"
        });
        return;
      }
      this.setData({
        dialogShow: false
      })
      wx.navigateTo({
        url: '/pages/signupV3/info?carModel=' + this.data.carModel
      })
      return
    }
    this.setData({
      dialogShow: false,
      carModel: ''
    })
  },
  select: function (event) {
    var type = event.currentTarget.dataset.type;
    var that = this;
    that.setData({
      carModel: type
    });
  },
  navigateToMySignInfo: function () {
    if (this.data.hasLogin) {
      //获取报名信息和当前报名进度 已缴费、公安审核中、公安审核通过、公安审核未过及原因
      wx.navigateTo({
        url: '/pages/signupinfo/index',
      })
    } else {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    };
  }
})
